package pub.wkq.auth;

import com.google.zxing.BarcodeFormat;
import com.google.zxing.EncodeHintType;
import com.google.zxing.WriterException;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.qrcode.QRCodeWriter;
import org.junit.Test;
import org.springframework.boot.test.context.SpringBootTest;

import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

@SpringBootTest
public class CustomColorQRCodeGenerator {
    @Test
    public void test() throws WriterException, IOException {
        String text = "https://img.wkq.pub/img/image-20230604210651908.png";
        int width = 300;
        int height = 300;
        String filePath = "custom_color_qrcode.png";
        String format = "png";
        Color foregroundColor = Color.BLUE;//自定义二维码颜色
        Color backgroundColor = Color.YELLOW;//自定义背景色

        QRCodeWriter qrCodeWriter = new QRCodeWriter();
        // 设置QRCode编码参数
        Map<EncodeHintType, Object> hints = new HashMap<>();
        hints.put(EncodeHintType.CHARACTER_SET, "UTF-8");
        hints.put(EncodeHintType.MARGIN, 1);

        BitMatrix bitMatrix = qrCodeWriter.encode(text, BarcodeFormat.QR_CODE, width, height, hints);
        //创建BufferedImage 对象，设置宽高和颜色模式
        BufferedImage bufferedImage = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
        //绘制彩色二维码
        Graphics graphics = bufferedImage.getGraphics();
        graphics.setColor(backgroundColor);
        graphics.fillRect(0, 0, width, height);
        graphics.setColor(foregroundColor);
        for (int x = 0; x < width; x++) {
            for (int y = 0; y < height; y++) {
                if (bitMatrix.get(x, y)) {
                    graphics.fillRect(x, y, 1, 1);
                }
            }
        }
        //保存生成的彩色二维码图片
        ImageIO.write(bufferedImage, format, new File(filePath));
        System.out.println("");
    }

}
